<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG 知识库问答系统</title>
    <link rel="icon" type="image/svg+xml" href="static/favicon.svg">
    <script src="static/js/tailwindcss.js"></script>

    <link href="static/css/font-awesome.min.css" rel="stylesheet">
    <script src="static/js/markdown-it.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#6366F1',
                        user: '#E3F2FD',
                        ai: '#F5F5F5',
                        dark: '#1F2937'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .scrollbar-thin {
                scrollbar-width: thin;
            }

            .scrollbar-thin::-webkit-scrollbar {
                width: 4px;
            }

            .scrollbar-thin::-webkit-scrollbar-thumb {
                background-color: rgba(156, 163, 175, 0.5);
                border-radius: 2px;
            }

            .typing-indicator {
                display: inline-flex;
                align-items: center;
            }

            .typing-indicator span {
                height: 0.5rem;
                width: 0.5rem;
                margin: 0 0.15rem;
                background-color: #9CA3AF;
                border-radius: 50%;
                display: block;
                animation: typing 1.4s infinite ease-in-out both;
            }

            .typing-indicator span:nth-child(1) {
                animation-delay: -0.32s;
            }

            .typing-indicator span:nth-child(2) {
                animation-delay: -0.16s;
            }

            @keyframes typing {
                0% {
                    transform: translateY(0px);
                }
                28% {
                    transform: translateY(-5px);
                }
                44% {
                    transform: translateY(0px);
                }
            }
        }

        .group-hover\:opacity-100 {
            opacity: 0;
        }

        .hover\:bg-gray-50:hover .group-hover\:opacity-100 {
            opacity: 1;
        }

        /* 新增：会话标题截断样式（12字符限制） */
        .session-title-truncate {
            /* 核心：强制不换行 + 隐藏超出内容 + 显示省略号 */
            white-space: nowrap; /* 禁止标题换行 */
            overflow: hidden; /* 隐藏超出容器的内容 */
            text-overflow: ellipsis; /* 超出部分显示... */

            /* 关键：控制最大宽度 = 12个中文字符宽度（中文字符约16px/个，12个≈192px，可根据字体微调） */
            max-width: 192px;

            /* 兼容英文字符（避免单个长单词撑破容器） */
            word-break: keep-all;
        }

        .active {
            border-left-width: 4px;
            border-left-color: rgb(59 130 246) !important;
        }

        .bg-ai {
            background: #f8f9fa;
            color: #333;
            padding: 16px;
            border-radius: 8px;
            border-top-left-radius: 0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            margin: 1rem 0;
            white-space: pre-wrap; /* 关键：保留换行符 */
            word-wrap: break-word;
            line-height: 1.5;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        }

        .think-section {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 12px;
            margin: 12px 0;
            border-radius: 4px;
            font-style: italic;
            color: #555;
        }

        /* 代码块样式 */
        .md-code-block {
            border: 1px solid #e1e4e8;
            border-radius: 6px;
            margin: 16px 0;
            background: white;
            font-size: 0;
        }

        .code-header {
            min-height: 32px;
            line-height: 1;
            background: #f6f8fa;
            padding: 8px 12px;
            border-bottom: 1px solid #e1e4e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }

        .language-label {
            color: #586069;
            font-weight: 600;
        }

        .code-actions button {
            background: white;
            border: 1px solid #d0d7de;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            color: #24292e;
        }

        .code-actions button:hover {
            background: #f3f4f6;
        }

        .md-code-block pre {
            margin: 0;
            padding: 16px;
            overflow-x: auto;
            background: white;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.45;
        }

        .md-code-block code {
            background: transparent !important;
            padding: 0 !important;
        }
    </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen flex flex-col">
<div class="flex flex-col h-screen max-h-screen overflow-hidden">
    <!-- 顶部导航 -->
    <header class="bg-white border-b border-gray-200 p-4 shadow-sm z-10">
        <div class="max-w-7xl mx-auto flex items-center justify-between">
            <h1 class="text-xl font-bold text-gray-800 flex items-center">
                <i class="fa fa-comments-o text-primary mr-2"></i>
                RAG 知识库问答系统
            </h1>
            <div class="flex items-center space-x-3">
                <button id="knowledge-btn"
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 py-2 px-4 rounded-md flex items-center transition-colors">
                    <i class="fa fa-database mr-2"></i> 知识库
                </button>
                <button id="new-chat-btn"
                        class="bg-primary hover:bg-primary/90 text-white py-2 px-4 rounded-md flex items-center transition-colors">
                    <i class="fa fa-plus mr-2"></i> 新对话
                </button>
            </div>
        </div>
    </header>

    <div class="flex-1 flex overflow-hidden">
        <!-- 左侧会话列表 -->
        <div id="sessions-sidebar"
             class="w-80 bg-white border-r border-gray-200 flex-shrink-0 hidden md:block overflow-y-auto scrollbar-thin">
            <div class="p-3 border-b border-gray-200">
                <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wider px-3">历史会话</h2>
            </div>
            <div id="sessions-list" class="divide-y divide-gray-100">
                <!-- 会话列表将通过JavaScript动态加载 -->
                <div class="p-4 text-center text-gray-500">
                    <i class="fa fa-history text-2xl mb-2 opacity-30"></i>
                    <p>加载会话历史中...</p>
                </div>
            </div>
        </div>

        <!-- 中间聊天区域 -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- 聊天内容区 -->
            <div id="chat-messages" class="flex-1 overflow-y-auto p-4 md:p-6 space-y-6 scrollbar-thin bg-gray-50">
                <!-- 欢迎消息 -->
                <div id="welcome-message" class="flex justify-center pt-8">
                    <div class="bg-white rounded-lg shadow-sm p-6 max-w-2xl w-full text-center">
                        <i class="fa fa-lightbulb-o text-4xl text-yellow-500 mb-4"></i>
                        <h2 class="text-xl font-semibold text-gray-800 mb-2">欢迎使用 RAG 知识库问答系统</h2>
                        <p class="text-gray-600 mb-4">我可以基于知识库中的信息回答您的问题。请输入您想了解的内容。</p>
                        <div class="flex flex-wrap justify-center gap-2 mt-4">
                            <span class="text-xs bg-gray-100 text-gray-700 px-3 py-1 rounded-full">知识问答</span>
                            <span class="text-xs bg-gray-100 text-gray-700 px-3 py-1 rounded-full">代码评审</span>
                            <span class="text-xs bg-gray-100 text-gray-700 px-3 py-1 rounded-full">SQL分析</span>
                            <span class="text-xs bg-gray-100 text-gray-700 px-3 py-1 rounded-full">单元测试生成</span>
                        </div>
                    </div>
                </div>
                <!-- 聊天消息将通过JavaScript动态添加 -->
            </div>

            <!-- 相关文档显示区 -->
            <div id="related-docs-container" class="bg-gray-50 border-t border-gray-200 p-4 hidden">
                <div class="flex items-center justify-between mb-2">
                    <h3 class="text-sm font-semibold text-gray-700">相关知识库内容</h3>
                    <button id="close-related-docs" class="text-gray-400 hover:text-gray-600">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <div id="related-docs" class="space-y-3 max-h-40 overflow-y-auto scrollbar-thin">
                    <!-- 相关文档将通过JavaScript动态添加 -->
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="bg-white border-t border-gray-200 p-4">
                <div class="max-w-4xl mx-auto">
                    <div class="mb-3">
                        <select id="scenario-select" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                            <option value="knowledge_qa">知识问答</option>
                            <option value="code_review">代码改动评审</option>
                            <option value="sql_review">SQL脚本评审</option>
                            <option value="unit_test">生成单元测试</option>
                        </select>
                    </div>
                    <div class="relative">
                            <textarea
                                    id="user-input"
                                    placeholder="请输入您的问题..."
                                    class="w-full pl-4 pr-12 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all resize-none"
                                    rows="3"
                            ></textarea>
                        <button id="send-btn"
                                class="absolute right-3 bottom-3 text-primary hover:text-primary/80 disabled:opacity-50 disabled:cursor-not-allowed">
                            <i class="fa fa-paper-plane text-xl"></i>
                        </button>
                    </div>
                    <p class="text-xs text-gray-500 mt-2 text-center">
                        按 Shift+Enter 换行，按 Enter 发送
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentSessionId = null;
    let isProcessing = false;
    let abortController = null;
    let md = null;
    // DOM 元素
    const chatMessages = document.getElementById('chat-messages');
    const userInput = document.getElementById('user-input');
    const sendBtn = document.getElementById('send-btn');
    const sessionsList = document.getElementById('sessions-list');
    const newChatBtn = document.getElementById('new-chat-btn');
    const knowledgeBtn = document.getElementById('knowledge-btn');
    const welcomeMessage = document.getElementById('welcome-message');
    const scenarioSelect = document.getElementById('scenario-select');
    const relatedDocsContainer = document.getElementById('related-docs-container');
    const relatedDocs = document.getElementById('related-docs');
    const closeRelatedDocs = document.getElementById('close-related-docs');


    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 页面加载完成后执行
        md = window.markdownit({
            highlight: function (str, lang) {
                // 创建自定义代码块
                return createCustomCodeBlock(str, lang);
            }
        });
        loadSessions();

        // 事件监听
        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keydown', handleKeyPress);
        newChatBtn.addEventListener('click', startNewChat);
        knowledgeBtn.addEventListener('click', () => window.location.href = '/knowledge.html');
        closeRelatedDocs.addEventListener('click', () => {
            relatedDocsContainer.classList.add('hidden');
        });

        // 窗口大小变化时重新调整布局
        window.addEventListener('resize', adjustLayout);
    });


    // 处理 DeepSeek 响应
    function processDeepSeekResponse(html) {
        // 1. 处理 think 部分
        html = html.replace(/<think>([\s\S]*?)<\/think>/g, function (match, thinkContent) {
            return `<div class="think-section">${thinkContent.trim()}</div>`;
        });

        // 2. 处理代码块 - 将 ```language code ``` 转换为 markdown-it 可处理的格式
        html = html.replace(/```(\w+)\n([\s\S]*?)```/g, function (match, lang, code) {
            const mdInfo = `\`\`\`${lang}\n${code}\`\`\``;
            return md.render(mdInfo);
        });

        return html;
    }

    // 创建自定义代码块
    function createCustomCodeBlock(str, lang) {
        const escapedCode = md.utils.escapeHtml(str);
        return `
<div class="md-code-block">
    <div class="code-header">
        <span class="language-label">${lang || 'text'}</span>
        <div class="code-actions">
            <button onclick="copyCode(this)">复制代码</button>
        </div>
    </div>
    <pre><code class="language-${lang}">${escapedCode}</code></pre>
</div>`;
    }

    // 加载会话列表

    async function loadSessions() {
        try {
            const response = await fetch('/api/sessions');
            if (!response.ok) throw new Error('加载会话失败');

            const sessions = await response.json();

            if (sessions.length === 0) {
                sessionsList.innerHTML = `
                <div class="p-4 text-center text-gray-500">
                    <i class="fa fa-file-text-o text-2xl mb-2 opacity-30"></i>
                    <p>暂无会话历史</p>
                </div>
            `;
                return;
            }

            // 渲染会话列表（新增删除按钮）
            sessionsList.innerHTML = '';
            sessions.forEach(session => {
                const sessionEl = document.createElement('div');
                sessionEl.id = session.id
                sessionEl.className = `p-3 hover:bg-gray-50 cursor-pointer transition-colors flex items-center justify-between`;

                // 关键修改：给标题div添加 title 属性（hover显示完整标题）+ 自定义截断类
                sessionEl.innerHTML = `
        <div class="flex-1 pr-2" onclick="loadSession('${session.id}')">
            <!-- 核心修改：title="${session.last_message}" + session-title-truncate 类 -->
            <div class="text-sm font-medium text-gray-800 session-title-truncate"
                 title="${session.last_message}">${session.last_message}</div>
            <div class="text-xs text-gray-500 mt-1">${formatDate(session.updated_at)}</div>
        </div>
        <button class="delete-session-btn text-gray-400 hover:text-red-500 transition-colors p-1 opacity-0 group-hover:opacity-100"
                data-session-id="${session.id}">
            <i class="fa fa-trash-o"></i>
        </button>
    `;
                sessionsList.appendChild(sessionEl);
            });

            // 为所有删除按钮绑定点击事件（委托绑定，避免动态元素问题）
            sessionsList.addEventListener('click', (e) => {
                const deleteBtn = e.target.closest('.delete-session-btn');
                if (deleteBtn) {
                    e.stopPropagation(); // 阻止事件冒泡（避免触发「加载会话」）
                    const sessionId = deleteBtn.getAttribute('data-session-id');
                    deleteSession(sessionId); // 执行删除逻辑
                }
            });

        } catch (error) {
            console.error('加载会话失败:', error);
            sessionsList.innerHTML = `
            <div class="p-4 text-center text-red-500">
                <i class="fa fa-exclamation-circle mr-2"></i>
                加载会话失败，请刷新页面重试
            </div>
        `;
        }
    }

    // 加载特定会话
    async function loadSession(sessionId) {
        if (isProcessing) return;

        try {
            showLoading();

            // 更新当前会话ID
            currentSessionId = sessionId;

            // 隐藏欢迎消息
            welcomeMessage.classList.add('hidden');

            // 清空当前聊天内容
            chatMessages.innerHTML = '';

            // 加载会话消息
            const response = await fetch(`/api/sessions/${sessionId}/messages`);
            if (!response.ok) throw new Error('加载会话消息失败');

            const messages = await response.json();

            // 显示消息
            messages.forEach(message => {
                addMessageToChat(message.content, message.is_user);
            });

            // 更新会话列表选中状态
            document.querySelectorAll('#sessions-list > div').forEach(el => {
                el.classList.remove('bg-blue-50', 'active');
            });
            const selectedElement = document.getElementById(sessionId);

            // 确保元素存在
            if (selectedElement) {
                selectedElement.classList.add('bg-blue-50', 'active');
            }


            // 滚动到底部
            scrollToBottom();
        } catch (error) {
            console.error('加载会话失败:', error);
            showNotification('加载会话失败', 'error');
        } finally {
            hideLoading();
        }
    }


    /**
     * 删除会话
     * @param {string} sessionId - 要删除的会话ID
     */
    async function deleteSession(sessionId) {
        // 1. 确认删除（防止误操作）
        const isConfirm = confirm('确定要删除该会话吗？删除后不可恢复！');
        if (!isConfirm) return;

        try {
            // 2. 发送DELETE请求（调用接口）
            const response = await fetch(`api/sessions/${sessionId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`删除失败：${response.statusText}`);
            }

            // 3. 成功后更新状态
            showNotification('会话删除成功', 'success');

            // 3.1 若删除的是「当前正在查看的会话」，清空聊天区并显示欢迎消息
            if (sessionId === currentSessionId) {
                currentSessionId = null;
                chatMessages.innerHTML = '';
                welcomeMessage.classList.remove('hidden');
                relatedDocsContainer.classList.add('hidden'); // 隐藏相关文档
            }

            // 3.2 重新加载会话列表（刷新UI）
            await loadSessions();

        } catch (error) {
            // 4. 失败处理
            console.error('删除会话出错:', error);
            showNotification(`删除失败：${error.message}`, 'error');
        }
    }

    // 开始新对话
    function startNewChat() {
        if (isProcessing) return;

        currentSessionId = null;
        chatMessages.innerHTML = '';
        welcomeMessage.classList.remove('hidden');
        relatedDocsContainer.classList.add('hidden');

        // 更新会话列表选中状态
        document.querySelectorAll('#sessions-list > div').forEach(el => {
            el.classList.remove('bg-blue-50', 'border-l-4', 'border-primary');
        });

        // 聚焦输入框
        userInput.focus();
    }

    // 发送消息
    function sendMessage() {
        const message = userInput.value.trim();
        if (!message || isProcessing) return;

        // 清空输入框
        userInput.value = '';

        // 隐藏欢迎消息
        welcomeMessage.classList.add('hidden');

        // 添加用户消息到聊天窗口
        addMessageToChat(message, true);

        // 显示AI正在输入
        const aiMessageEl = addMessageToChat('', false, true);

        // 滚动到底部
        scrollToBottom();

        // 处理流式响应
        processStream(message, aiMessageEl);
    }

    // 处理流式响应 - 使用fetch API发送POST请求
    async function processStream(message, aiMessageEl) {
        isProcessing = true;
        sendBtn.disabled = true;

        // 如果有正在进行的请求，终止它
        if (abortController) {
            abortController.abort();
        }

        // 创建新的AbortController
        abortController = new AbortController();

        try {
            // 准备请求数据
            const requestData = {
                question: message,
                session_id: currentSessionId || '',
                scenario: scenarioSelect.value
            };

            // 发送POST请求
            const response = await fetch('/api/query/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData),
                signal: abortController.signal,
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            if (!response.body) {
                throw new Error('响应没有内容');
            }

            // 存储完整响应
            let fullResponse = '';

            // 处理流式响应
            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            while (true) {
                const {done, value} = await reader.read();

                if (done) {
                    break;
                }

                // 解码接收到的字节
                const chunk = decoder.decode(value, {stream: true});

                // 分割SSE消息
                const lines = chunk.split('\n');

                for (const line of lines) {
                    const trimmedLine = line.trim();
                    if (trimmedLine.startsWith('data:')) {
                        const data = trimmedLine.slice(5).trim();
                        if (data) {
                            try {
                                const parsed = JSON.parse(data);

                                if (parsed.chunk) {
                                    // 添加新的响应块
                                    fullResponse += parsed.chunk;
                                    updateAiMessage(aiMessageEl, fullResponse, false);
                                    scrollToBottom();
                                }

                                if (parsed.done) {
                                    // 响应完成
                                    currentSessionId = parsed.session_id;
                                    loadSessions();

                                    // 显示相关文档
                                    if (parsed.related_documents && parsed.related_documents.length > 0) {
                                        showRelatedDocuments(parsed.related_documents);
                                    }
                                }
                            } catch (e) {
                                console.error('解析流式数据失败:', e);
                            }
                        }
                    }
                }
            }
        } catch (error) {
            if (error.name !== 'AbortError') { // 忽略主动中止的错误
                console.error('处理流式响应失败:', error);
                showNotification('处理响应失败', 'error');
                updateAiMessage(aiMessageEl, '抱歉，处理请求时发生错误，请重试。', false);
            }
        } finally {
            isProcessing = false;
            sendBtn.disabled = false;
            abortController = null;
        }
    }

    function getIcon(isUser) {
        if (isUser) {
            return `<i class="fa fa-user"></i>`
        } else {
            return `<img src="static/favicon.svg" alt="SVG Image">`
        }
    }

    // 添加消息到聊天窗口
    function addMessageToChat(content, isUser, isLoading = false) {
        const messageEl = document.createElement('div');
        messageEl.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`;

        const bubbleClass = isUser
            ? 'bg-user text-gray-800'
            : 'bg-ai text-gray-800';

        messageEl.innerHTML = `
                <div class="flex max-w-[85%] ${isUser ? 'flex-row-reverse' : ''}">
                    <div class="flex-shrink-0 h-8 w-8 rounded-full ${isUser ? 'bg-primary' : ''} flex items-center justify-center text-white">
                        ${getIcon(isUser)}
                    </div>
                    <div class="ml-2 mr-2 ${isUser ? 'mr-0 ml-2' : ''}">
                        <div class="${bubbleClass} p-4 rounded-lg rounded-t-${isUser ? 'right' : 'left'}-none shadow-sm">
                            ${isLoading ? getTypingIndicator() : formatMessage(content)}
                        </div>
                    </div>
                </div>
            `;

        chatMessages.appendChild(messageEl);
        return messageEl.querySelector('.rounded-lg');
    }

    // 更新AI消息内容
    function updateAiMessage(element, content, done = true) {
        element.innerHTML = done ? formatMessage(content) : formatMessage(content);
    }

    // 获取打字指示器
    function getTypingIndicator() {
        return `
                <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            `;
    }

    function attachCopyHandlers() {
        // 事件委托处理复制按钮点击
        document.addEventListener('click', function (e) {
            if (e.target.closest('.code-actions button')) {
                const button = e.target.closest('.code-actions button');
                const codeBlock = button.closest('.md-code-block');
                const code = codeBlock.querySelector('code').textContent;

                navigator.clipboard.writeText(code).then(() => {
                    const originalText = button.textContent;
                    button.textContent = '已复制!';
                    setTimeout(() => {
                        button.textContent = originalText;
                    }, 2000);
                }).catch(err => {
                    console.error('复制失败:', err);
                    button.textContent = '复制失败';
                    setTimeout(() => {
                        button.textContent = '复制代码';
                    }, 2000);
                });
            }
        });
    }

    // 全局复制函数（用于 onclick）
    window.copyCode = function (button) {
        const codeBlock = button.closest('.md-code-block');
        const code = codeBlock.querySelector('code').textContent;

        navigator.clipboard.writeText(code).then(() => {
            const originalText = button.textContent;
            button.textContent = '已复制!';
            setTimeout(() => {
                button.textContent = originalText;
            }, 2000);
        });
    }


    // 格式化消息内容（简单处理换行）
    // 格式化消息内容（简单处理换行）
    function formatMessage(content) {
        if (!content) return '';

        const processedHtml = processDeepSeekResponse(content);

        // 将内容包装成 markdown 格式
        const markdownContent = processedHtml
            .replace(/<div[^>]*>/g, '')  // 移除 div 标签
            .replace(/<\/div>/g, '')     // 移除闭合 div
            .replace(/<think-section>/g, '')  // 移除 think-section 标签
            .replace(/<\/think-section>/g, ''); // 移除闭合 think-section

        // 使用 markdown-it 渲染
        const rendered = md.render(markdownContent);

        // 手动处理 think 部分（markdown-it 不会处理我们自定义的 think-section）
        const finalHtml = processedHtml.replace(
            /<think-section>([\s\S]*?)<\/think-section>/g,
            '<div class="think-section">$1</div>'
        );
        attachCopyHandlers();
        return finalHtml
    }

    // 显示相关文档
    function showRelatedDocuments(documents) {
        relatedDocs.innerHTML = '';

        documents.forEach((doc, index) => {
            const docEl = document.createElement('div');
            docEl.className = 'bg-white p-3 rounded-md border border-gray-200 text-sm';

            // 截断长文档
            const shortDoc = doc.length > 150 ? doc.substring(0, 150) + '...' : doc;

            docEl.innerHTML = `
                    <div class="flex items-start">
                        <div class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded mr-2 mt-0.5">
                            来源 ${index + 1}
                        </div>
                        <div class="flex-1">${shortDoc}</div>
                    </div>
                `;

            relatedDocs.appendChild(docEl);
        });

        relatedDocsContainer.classList.remove('hidden');
    }

    // 处理按键事件
    function handleKeyPress(e) {
        // 按Enter发送消息，Shift+Enter换行
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    }

    // 滚动到聊天底部
    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 显示加载状态
    function showLoading() {
        // 可以在这里实现全局加载状态
    }

    // 隐藏加载状态
    function hideLoading() {
        // 可以在这里实现全局加载状态
    }

    // 显示通知
    function showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500 text-white' :
                type === 'error' ? 'bg-red-500 text-white' :
                    'bg-blue-500 text-white'
        } transform translate-y-20 opacity-0 transition-all duration-300`;
        notification.textContent = message;

        // 添加到页面
        document.body.appendChild(notification);

        // 显示通知
        setTimeout(() => {
            notification.classList.remove('translate-y-20', 'opacity-0');
        }, 10);

        // 3秒后隐藏通知
        setTimeout(() => {
            notification.classList.add('translate-y-20', 'opacity-0');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffInSeconds = Math.floor((now - date) / 1000);

        if (diffInSeconds < 60) {
            return `${diffInSeconds}秒前`;
        } else if (diffInSeconds < 3600) {
            return `${Math.floor(diffInSeconds / 60)}分钟前`;
        } else if (diffInSeconds < 86400) {
            return `${Math.floor(diffInSeconds / 3600)}小时前`;
        } else if (diffInSeconds < 604800) {
            return `${Math.floor(diffInSeconds / 86400)}天前`;
        } else {
            return `${date.getMonth() + 1}月${date.getDate()}日`;
        }
    }

    // 调整布局
    function adjustLayout() {
        // 可以根据需要实现响应式布局调整
    }
</script>
</body>
</html>
